package bb.lanxing.lib.devices.base;

import android.bluetooth.BluetoothGattCharacteristic;
import android.util.SparseArray;
import bb.lanxing.lib.devices.core.ble.IGattClient;
import java.util.ArrayList;
import java.util.List;

public class BleDataDispatcher {
    private static BleDataDispatcher INSTANCE;
    private SparseArray<List<CharacteristicConverter>> mDataConverterSet;

    private void init() {
    }

    public static BleDataDispatcher getInstance() {
        synchronized (BleDataDispatcher.class) {
            if (INSTANCE == null) {
                BleDataDispatcher bleDataDispatcher = new BleDataDispatcher();
                INSTANCE = bleDataDispatcher;
                bleDataDispatcher.init();
            }
        }
        return INSTANCE;
    }

    private BleDataDispatcher() {
    }

    public synchronized void dispatch(IGattClient iGattClient, BluetoothGattCharacteristic bluetoothGattCharacteristic) {
        if (this.mDataConverterSet == null) {
            return;
        }
        int i = 2;
        int type = iGattClient.getType() == 6 ? 2 : iGattClient.getType();
        if (iGattClient.getType() != 19) {
            i = type;
        }
        List<CharacteristicConverter> list = this.mDataConverterSet.get(i);
        if (list != null) {
            for (CharacteristicConverter characteristicConverter : list) {
                characteristicConverter.convert(iGattClient, bluetoothGattCharacteristic);
            }
        }
    }

    public void addConverter(int i, CharacteristicConverter characteristicConverter) {
        if (this.mDataConverterSet == null) {
            this.mDataConverterSet = new SparseArray<>();
        }
        List<CharacteristicConverter> list = this.mDataConverterSet.get(i);
        if (list == null) {
            ArrayList arrayList = new ArrayList();
            arrayList.add(characteristicConverter);
            this.mDataConverterSet.put(i, arrayList);
            return;
        }
        list.add(characteristicConverter);
    }

    public void removeConverter(int i, CharacteristicConverter characteristicConverter) {
        List<CharacteristicConverter> list;
        SparseArray<List<CharacteristicConverter>> sparseArray = this.mDataConverterSet;
        if (sparseArray == null || (list = sparseArray.get(i)) == null) {
            return;
        }
        list.remove(characteristicConverter);
    }

    public static void terminate() {
        synchronized (BleDataDispatcher.class) {
            BleDataDispatcher bleDataDispatcher = INSTANCE;
            if (bleDataDispatcher == null) {
                return;
            }
            SparseArray<List<CharacteristicConverter>> sparseArray = bleDataDispatcher.mDataConverterSet;
            if (sparseArray != null) {
                sparseArray.clear();
                bleDataDispatcher.mDataConverterSet = null;
            }
            INSTANCE = null;
        }
    }
}
